using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.Practices.EnterpriseLibrary.Configuration.Design;
using Microsoft.Practices.EnterpriseLibrary.PolicyInjection.Configuration.Design;
using Microsoft.Practices.EnterpriseLibrary.PolicyInjection.Configuration.Design.MatchingRules;
using Microsoft.Practices.EnterpriseLibrary.PolicyInjection.Configuration;

namespace EntLibContrib.PolicyInjection.Design
{
    class PolicyInjectionNodeBuilder : NodeBuilder
    {
        public PolicyInjectionNodeBuilder(IServiceProvider serviceProvider)
            : base(serviceProvider)
        {
        }

        public void BuildAdditionalMatchingRuleNodes(MatchingRuleCollectionNode matchingRuleNodes)
        {
            foreach (MatchingRuleNode ruleNode in matchingRuleNodes.Nodes)
            {
                ICompositeMatchingRuleNode compositeRule = ruleNode as ICompositeMatchingRuleNode;
                if (compositeRule != null)
                {
                    BuildComposite(compositeRule);
                }
            }
        }

        private void BuildComposite(ICompositeMatchingRuleNode compositeRule)
        {
            foreach (MatchingRuleData containedRuleData in compositeRule.ChildRules)
            {
                ConfigurationNode ruleNode = NodeCreationService.CreateNodeByDataType(containedRuleData.GetType(), new object[] { containedRuleData });
                ((ConfigurationNode)compositeRule).AddNode(ruleNode);

                ICompositeMatchingRuleNode compositeChildRule = ruleNode as ICompositeMatchingRuleNode;
                if (compositeChildRule != null)
                {
                    BuildComposite(compositeChildRule);
                }
            }
        }
    }
}
